// services/wordService.js
const connection = require('../database'); // 确保您有数据库连接

// 获取特定 wordset 的单词
const getWordsFromWordset = (wordsetId, num, callback) => {
    const getWordsetWordsQuery = `
    SELECT wordlist
    FROM wordsets
    WHERE id = ?
  `;
    connection.query(getWordsetWordsQuery, [wordsetId], (error, results) => {
        if (error) return callback(error, null);
        // 假设 wordsets 表的 words 字段包含了单词ID的JSON数组
        let wordIds = results[0].wordlist;
        // 随机选取 num 个单词
        wordIds = selectRandomElements(wordIds, num);
        console.log(wordIds.toString());
        // 从 words 表获取单词
        const getWordsQuery = `
            SELECT *
            FROM words
            WHERE id IN (${wordIds.toString()})
        `;
        connection.query(getWordsQuery, '', callback);
    });
};

// 从整个 words 表中随机获取单词作为选项
const getRandomWords = (num, excludedWords, callback) => {
    let query = `
    SELECT name
    FROM words
    WHERE name NOT IN (?)
    ORDER BY RAND()
    LIMIT ?
  `;
    connection.query(query, [excludedWords.toString(), num], callback);
};

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}
function selectRandomElements(array, num) {
    if(!array) return [];
    const shuffled = [...array].sort(() => 0.5 - Math.random());
    const arrayOfIds = shuffled.map(obj => obj.id);
    return arrayOfIds.slice(0, num);
}
module.exports = {
    getWordsFromWordset,
    getRandomWords,
    selectRandomElements,
    shuffleArray,
};